﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Admin.NET.Application.Entity;
namespace Admin.NET.Application;

/// <summary>
/// 计划延期参数服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public partial class PlanDelayConfigService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<PlanDelayConfig> _planDelayConfigRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public PlanDelayConfigService(SqlSugarRepository<PlanDelayConfig> planDelayConfigRep, ISqlSugarClient sqlSugarClient)
    {
        _planDelayConfigRep = planDelayConfigRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询计划延期参数 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询计划延期参数")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<PlanDelayConfigOutput>> Page(PagePlanDelayConfigInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _planDelayConfigRep.AsQueryable()
            .WhereIF(input.DelayDays != null, u => u.DelayDays == input.DelayDays)
            .WhereIF(input.ClassNameId != null, u => u.ClassNameId == input.ClassNameId)
            .LeftJoin<PlanType>((u, className) => u.ClassNameId == className.Id)
            .Select((u, className) => new PlanDelayConfigOutput
            {
                Id = u.Id,
                DelayDays = u.DelayDays,
                ClassNameId = u.ClassNameId,
                ClassNameFkDisplayName = $"{className.Name}",
                TenantId = u.TenantId,
                IsDelete = u.IsDelete,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
            });
		return await query.ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取计划延期参数详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取计划延期参数详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<PlanDelayConfig> Detail([FromQuery] QueryByIdPlanDelayConfigInput input)
    {
        return await _planDelayConfigRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加计划延期参数 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加计划延期参数")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddPlanDelayConfigInput input)
    {
        var entity = input.Adapt<PlanDelayConfig>();
        return await _planDelayConfigRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新计划延期参数 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新计划延期参数")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdatePlanDelayConfigInput input)
    {
        var entity = input.Adapt<PlanDelayConfig>();
        await _planDelayConfigRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除计划延期参数 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除计划延期参数")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeletePlanDelayConfigInput input)
    {
        var entity = await _planDelayConfigRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _planDelayConfigRep.FakeDeleteAsync(entity);   //假删除
        //await _planDelayConfigRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除计划延期参数 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除计划延期参数")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeletePlanDelayConfigInput> input)
    {
        var exp = Expressionable.Create<PlanDelayConfig>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _planDelayConfigRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _planDelayConfigRep.FakeDeleteAsync(list);   //假删除
        //return await _planDelayConfigRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataPlanDelayConfigInput input)
    {
        var classNameIdData = await _planDelayConfigRep.Context.Queryable<PlanType>()
            .InnerJoinIF<PlanDelayConfig>(input.FromPage, (u, r) => u.Id == r.ClassNameId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.Name}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "classNameId", classNameIdData },
        };
    }
    
    /// <summary>
    /// 导出计划延期参数记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出计划延期参数记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PagePlanDelayConfigInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportPlanDelayConfigOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "计划延期参数导出记录");
    }
    
    /// <summary>
    /// 下载计划延期参数数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载计划延期参数数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportPlanDelayConfigOutput>(), "计划延期参数导入模板", (_, info) =>
        {
            if (nameof(ExportPlanDelayConfigOutput.ClassNameFkDisplayName) == info.Name) return _planDelayConfigRep.Context.Queryable<PlanType>().Select(u => $"{u.Name}").Distinct().ToList();
            return null;
        });
    }
    
    private static readonly object _planDelayConfigImportLock = new object();
    /// <summary>
    /// 导入计划延期参数记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入计划延期参数记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (_planDelayConfigImportLock)
        {
            var stream = ExcelHelper.ImportData<ImportPlanDelayConfigInput, PlanDelayConfig>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 分类
                    var classNameIdLabelList = pageItems.Where(x => x.ClassNameFkDisplayName != null).Select(x => x.ClassNameFkDisplayName).Distinct().ToList();
                    if (classNameIdLabelList.Any()) {
                        var classNameIdLinkMap = _planDelayConfigRep.Context.Queryable<PlanType>().Where(u => classNameIdLabelList.Contains($"{u.Name}")).ToList().ToDictionary(u => $"{u.Name}", u => u.Id  as long?);
                        pageItems.ForEach(e => {
                            e.ClassNameId = classNameIdLinkMap.GetValueOrDefault(e.ClassNameFkDisplayName ?? "");
                            if (e.ClassNameId == null) e.Error = "分类链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.DelayDays == null){
                            x.Error = "延期天数不能为空";
                            return false;
                        }
                        if (x.ClassNameId == null){
                            x.Error = "分类不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<PlanDelayConfig>>();
                    
                    var storageable = _planDelayConfigRep.Context.Storageable(rows)
                        .SplitInsert(_=> true) // 没有设置唯一键代表插入所有数据
                        .ToStorage();
                    
                    storageable.AsInsertable.ExecuteCommand();// 不存在插入
                    storageable.AsUpdateable.UpdateColumns(it => new
                    {
                        it.DelayDays,
                        it.ClassNameId,
                    }).ExecuteCommand();// 存在更新
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
